/* RgrConnectionHandler.java
 * Brent Woodhouse
 * This file contains code to handle the ringer connections for VOIP app.
*/
package project6.voip;

import java.net.*;
import java.io.*;

public class RgrConnectionHandler implements Runnable
{
	Socket socket;
	PrintWriter out;
	BufferedReader in;
	String user;
	boolean connected;
	String reply = null; // "yes" or "no"
	
	public RgrConnectionHandler(Socket sock)//The constructor copies the socket into the handler
	{
		socket = sock;
		user = null;
		connected = false;
		reply = "";
	}
	
	public void run()//The run method handles all the messages being sent by the client.
	{
		try
		{
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
			String input;
			
			while(true)
			{
				if(in.ready())
				{
					input = in.readLine();
					
					if (input.equals("Calling")){
						// Alert GUI to display reception activity and ring
						// Receive username of caller
						user = in.readLine();
						connected = true;
						
						// Wait for user to answer yes or no
						while (!reply.equals("yes") && !reply.equals("no")){
							try {
								wait(1000); // wait a second in between checks
							}
							catch (Exception e){;}
						}
						
						out.println(reply);
					}
					
					if (input.equals("End call")){
						connected = false;
					}
				}
				if(socket.isClosed())
				{
					System.out.println("Connection Handler exited.");
					return;
				}
			}
		}
		catch(IOException e)
		{
			System.out.println("Error in Connection Handler");
		}
	}
	
	public void setReply(String answer){
		reply = answer; // "yes" or "no"
	}
}
